/*
 * CacheEntry.cpp
 *
 *  Created on: 09.12.2012
 *      Author: zheka
 */

#include "CacheEntry.hpp"
#include <limits>
#include "proxy/CacheController.hpp"
#include "util/Log.hpp"
#include "pthread/ScopedLock.hpp"

const int CacheEntry::BUFFER_SIZE = 1024 * 10;

CacheEntry::CacheEntry() :
		count(0), disposable(false) {
	size = std::numeric_limits<int>::max();
}
void CacheEntry::lock() {
	locker.readLock();
}
void CacheEntry::unlock() {
	locker.unlock();
}
const std::string & CacheEntry::getData() {
	return data;
}
size_t CacheEntry::getSize() {
	return size;
}

void CacheEntry::add(const std::string & s) {
	buffer += s;
	if (buffer.length() >= BUFFER_SIZE) {
		locker.writeLock();
		data += buffer;
		locker.unlock();
		buffer.clear();
	}

}
void CacheEntry::finish() {
	locker.writeLock();
	data += buffer;
	size = data.size();
	locker.unlock();
	buffer.clear();
}

void CacheEntry::registerTask() {
	ScopedLock lock(mutex);
	count++;

}
void CacheEntry::unregisterTask() {
	ScopedLock lock(mutex);

	count--;
	if (count == 0 && disposable) {
		CacheController::getInstance().remove(this);
		Log::v("[CacheEntry] deleted");
		data.clear();
		// delete this;

	}

}

int CacheEntry::getClientCount() {
	ScopedLock lock(mutex);

	return count;
}
bool CacheEntry::isDisposable() {
	return disposable;
}
